#include <TimerService.h>

unsigned char flags=0;
unsigned char timers=10;

volatile static struct
{
	unsigned char position;
	unsigned int time;
} SoftTimer[10];

ISR(TIMER0_OVF_vect)
{
	int i;
	for (i=0;i<timers;i++)
	{
		if (SoftTimer[i].position==0xff)
		{
			continue;
		}

		if (SoftTimer[i].time!=0)
		{
			SoftTimer[i].time--;
		}
		else
		{
			flags|=(1<<SoftTimer[i].position);
			SoftTimer[i].position=0xff;
		}
	}

	TCNT0=0xdf;
}

void InitTimer()
{
	TIMSK=(1<<TOIE0);
	TCCR0=(1<<CS02)|(0<<CS01)|(0<<CS00);
}

void SetTimer(unsigned char newPosition, unsigned int newTime)
{
	cli();

	int i;
	for (i=0;i<timers;i++)
	{
		if (SoftTimer[i].position==newPosition)
		{
			SoftTimer[i].time=newTime;
			sei();
			return;

		}
	}

	for (i=0;i<timers;i++)
	{
		if (SoftTimer[i].position==0xff)
		{
			SoftTimer[i].position=newPosition;
			SoftTimer[i].time=newTime;
			sei();
			return;

		}
	}

	sei();
}
